import 'dart:io';

import 'package:base_moudle/index.dart';

import '../../../api/api.dart';
import '../../../config/zs_routers.dart';
import '../../../models/data_model/HyWorkModel.dart';
import '../../../models/data_model/ZsRedDotModel.dart';
import '../../../models/data_model/zs_project_detail_model.dart';
import '../../../models/data_model/zs_project_history_schedule.dart';
import '../../../models/data_model/zs_project_schedule_base_data.dart';
import '../../../models/data_model/zs_project_schedule_statistics_model.dart';
import '../../../models/data_model/zs_work_notice_list_model.dart';
import '../../../new_paltform/define/hy_event_bus.dart';
import '../../../new_paltform/define/hy_header.dart';
import '../../../new_paltform/utils/json_parse_utils.dart';
import '../../work/zs_work_route_logic.dart';
import '../db/work_app_model.dart';

typedef ProjectCallback = void Function(Map<String, dynamic> arg);

abstract class HyHomeGetxController extends GetxController with NetworkMixin {
  RxList<ItemModel> allList = <ItemModel>[].obs;
  RxList<ItemModel> timeList = <ItemModel>[].obs;
  RxList<ItemModel> itemList = <ItemModel>[].obs;

  Future<void> onAllData() async {}

  Future<void> onTimeList() async {}

  Future<void> onItemList() async {}

  ///管理时调用
  Future<void> onUpdateLike() async {}
}

class HyWorkHomeLogic extends HyHomeGetxController {
  RxBool caseBool = false.obs;
  RxString companyName = ''.obs;
  RxInt emailCount = 0.obs;
  RxBool canNew = false.obs;

  Rx<ProjectMap> projectDetail = ProjectMap().obs;
  final GlobalKey keyGreen = GlobalKey();

  ProjectCallback? callback;
  String projectId = '';

  Rx<ZsProjectHistorySchedule> projectSchedule = ZsProjectHistorySchedule().obs;
  Rx<TaskNum> taskNum = TaskNum().obs;
  RxBool isOpenMore = false.obs;
  RxList<ZsProjectScheduleStatisticsModel> scheduleList =
      <ZsProjectScheduleStatisticsModel>[].obs;

  RxDouble totalSchedule = RxDouble(0.0);
  RxString totalScheduler = ''.obs;
  RxString totalDays = ''.obs;
  RxString finishDays = ''.obs;
  RxBool overdue = false.obs;
  RxString projectStatus = ''.obs;

  bool hasSchedule = false; //默认没有项目进度
  ///判断是否项目内人员 默认没有
  RxBool hasProjectMember = false.obs;

  final Rx<PageStatus> pageStatus = PageStatus.loading.obs;
  final Rx<PageStatus> workStatus = PageStatus.loading.obs;

  ///协同办公信息
  RxList<ItemModel> webList = <ItemModel>[].obs;

  final bool isXB = ZsMemeryCache.loginDataModel?.userInfo?.companyId == COM_XB;

  final bool isCompanyId =
      ZsMemeryCache.loginDataModel?.userInfo?.companyId == '804';

  ///通知
  final RxList<ZsWorkNoticeListModel> noticeList =
      <ZsWorkNoticeListModel>[].obs;

  StreamSubscription? _subscription;

  final ZsWorkRouteLogic routeLogic = Get.put(ZsWorkRouteLogic());

  @override
  Future<void> onInit() async {
    _subscription = eventBus.on<HYEvent>().listen((HYEvent event) {
      if (event.type == HYEventType.refreshPage) {
        projectId = '';
        requestProjectDetail();
      }
    });
    super.onInit();
  }

  Future<void> roleLawcase() async {
    if (ZsMemeryCache.zsWorkLoginModel?.workPath != WorkPath_YM) {
      caseBool.value = false;
      return Future(() => null);
    }
    await get(
      path: '/lawcase/role',
      otherHost: WorkPath_YM,
      queryParams: <String, dynamic>{
        'userId': ZsMemeryCache.zsWorkLoginModel!.workModuleUserId ?? 0,
      },
    ).then((ResultData? value) {
      print(value?.responseData);
      caseBool.value = value?.responseData['data'];
      onAllData();
    });
  }

  @override
  Future<void> onAllData() async {
    final List<ItemModel> arr = ItemModel.all();
    final List<HyWorkAppModel> list = await HyWorkAppModel.allList();

    bool isManager = false;
    if (ZsMemeryCache.loginDataModel?.userInfo?.userId != null &&
        projectDetail.value.directorId.toString().contains(
            ZsMemeryCache.loginDataModel?.userInfo?.userId as String)) {
      isManager = true;
    }

    final bool isProjectShow =
        ZsMemeryCache.loginDataModel?.userInfo?.isProjectShow ?? false;
    final bool isOaShow =
        (ZsMemeryCache.loginDataModel?.userInfo?.isOaShow ?? false) && (ZsMemeryCache.loginDataModel?.userInfo?.isJuids ?? false);

    if (list.isEmpty) {
      int rank = 1;
      arr.forEach((ItemModel e) async {
        bool isEnabled = true;
        if (e.title == '诉讼案件') {
          isEnabled = caseBool.value;
        } else if (['自查统计', '专项检查统计','客户管理'].contains(e.title)) {
          isEnabled = isCompanyId;
        } else if (e.title == '线下工作') {
          isEnabled = routeLogic.hasProjectMember.value;
        } else if (ItemModel.managerList().contains(e.title)) {
          isEnabled = isManager;
        } else if (e.title == '我的签名') {
          isEnabled =
              ZsMemeryCache.loginDataModel?.userInfo?.companyId == COM_XB;
        }
        if (['办公工作', 'web'].contains(e.type)) {
          if (!isOaShow) {
            isEnabled = false;
          }
        } else {
          if (isProjectShow == false || (isProjectShow && !canNew.value)) {
            isEnabled = false;
          }
        }
        await HyWorkAppModel.saveModel(
            model: e, isEnabled: isEnabled, rank: rank);
        rank++;
      });
    } else {
      for (HyWorkAppModel item in list) {
        int isEnabled = -1;
        if (item.appName == '文档中心') {
          if (item.appType == '办公工作') {
            isEnabled = -2; //历史数据删除
          }
        } else if (item.appName == '诉讼案件') {
          isEnabled = caseBool.value ? 1 : 0;
        } else if (['自查统计', '专项检查统计','客户管理'].contains(item.appName)) {
          isEnabled = isCompanyId ? 1 : 0;
        } else if (item.appName == '线下工作') {
          isEnabled = routeLogic.hasProjectMember.value ? 1 : 0;
        } else if (ItemModel.managerList().contains(item.appName)) {
          isEnabled = isManager ? 1 : 0;
        } else if (item.appName == '我的签名') {
          isEnabled =
          ZsMemeryCache.loginDataModel?.userInfo?.companyId == COM_XB
              ? 1
              : 0;
        }
        if (['办公工作', 'web'].contains(item.appType)) {
          if (!isOaShow) {
            isEnabled = 0;
          } else {
            if (isEnabled == -1) {
              isEnabled = 1;
            }
          }
        } else {
          ///企业管理
          if (isProjectShow == false || (isProjectShow && !canNew.value)) {
            isEnabled = 0;
          } else {
            if (isEnabled == -1) {
              isEnabled = 1;
            }
          }
        }
        if (isEnabled == 0 || isEnabled == 1) {
          await item.saveKeyModel(dict: {'isEnabled': isEnabled});
        } else if (isEnabled == -2) {
          item.deleteDb();
        }
      }
      int rank = list.length + 1;
      for (final ItemModel e in arr) {
        if (list
            .where((HyWorkAppModel e1) =>
        e.title == e1.appName && e.type == e1.appType)
            .isNullOrEmpty()) {
          await HyWorkAppModel.saveModel(model: e, rank: rank);
          rank++;
        }
      }
    }

    ///统一权限有OA权限的 显示办公工作内容
    if ((ZsMemeryCache.loginDataModel?.userInfo?.isJuids ?? false) &&
        isOaShow) {
      final List<HyWorkAppModel> webArray =
      await HyWorkAppModel.allList(appType: 'web');

      if (webList.isEmpty && webArray.isNotEmpty) {
        for (final HyWorkAppModel element in webArray) {
          await element.saveKeyModel(dict: {'isEnabled': 0});
        }
      } else if (webList.isNotEmpty) {
        for (final HyWorkAppModel element in webArray) {
          final int isEnabled = webList
              .where((ItemModel p0) => p0.title == element.appName)
              .isNotEmpty
              ? 1
              : 0;
          await element.saveKeyModel(dict: {'isEnabled': isEnabled});
        }

        for (final ItemModel item in webList) {
          if (webArray
              .where((HyWorkAppModel element) => element.appName == item.title)
              .isEmpty) {
            await HyWorkAppModel.saveModel(model: item);
          } else {
            final Iterable<HyWorkAppModel> arr = webArray.where(
                    (HyWorkAppModel element) => element.appName == item.title);
            for (final HyWorkAppModel md in arr) {
              await md.saveKeyModel(
                  dict: {'iconName': item.iconName, 'isEnabled': 1});
            }
          }
        }
      }
    }

    allList.value = (await HyWorkAppModel.allList(isEnabled: true))
        .map((HyWorkAppModel e) => e.toModel())
        .toList();
    onTimeList();
    onItemList();
  }

  @override
  Future<void> onTimeList() async {
    timeList.value = (await HyWorkAppModel.timeList())
        .map((HyWorkAppModel e) => e.toModel())
        .toList();
  }

  @override
  Future<void> onItemList() async {
    itemList.value = (await HyWorkAppModel.allList(
        isEnabled: true, isShow: true, isRank: true))
        .map((HyWorkAppModel e) => e.toModel())
        .toList();
  }

  ///管理时调用
  @override
  Future<void> onUpdateLike() async {
    final List<HyWorkAppModel> list =
    await HyWorkAppModel.allList(isEnabled: true, isShow: true);

    for (final HyWorkAppModel item in list) {
      if (itemList
          .where((ItemModel p0) => p0.title == item.appName)
          .isEmpty) {
        await item.saveKeyModel(dict: {'isShow': 0});
      } else {
        final int rank = itemList.indexWhere(
                (ItemModel element) => element.title == item.appName) +
            1;
        await item.saveKeyModel(dict: {'rank': rank, 'isShow': 1});
      }
    }
    onAllData();
  }

  void loginWork() {
    if (ZsMemeryCache.loginDataModel == null ||
        ZsMemeryCache.loginDataModel!.userInfo == null) {
      print('----参数不全');
      workStatus.value = PageStatus.noLogin;

      /// 如果需要登录，跳转到登录页面去
      return;
    }
    final Map<String, dynamic> params = {};
    String loginPath = zsWorkLogin2;
    if (ZsMemeryCache.loginDataModel!.userInfo!.companyId == COM_XB) {
      loginPath = zsWorkLogin;
      params.putIfAbsent(
          'view', () => ZsMemeryCache.loginDataModel!.userInfo!.userName ?? '');
      params.putIfAbsent(
          'uid',
              () =>
          ZsMemeryCache.loginDataModel!.userInfo!.encryptionPassword ?? '');
    } else {
      params.putIfAbsent(
          'userId', () => ZsMemeryCache.zsWorkLoginModel?.workModuleUserId);
    }
    // spaceLogic.fromStonge();
    post(
        path: loginPath,
        otherHost: ZsMemeryCache.zsWorkLoginModel?.workPath,
        params: params)
        .then((ResultData? value) {
      if (value?.data != null) {
        final currentUser = value?.data['currentUser'];
        if (currentUser != null) {
          final String userId = currentUser['userId'].toString();
          final String orgId = currentUser['orgId'].toString();
          final String userName = currentUser['userName'].toString();
          final String? juid = ZsMemeryCache.loginDataModel?.userInfo?.juid;
          final String? juid2 = ZsMemeryCache.loginDataModel?.userInfo?.juid2;
          companyName.value = value!.data['companyName'] ??
              ZsMemeryCache.loginDataModel?.userInfo?.companyName;
          if (juid.isNotNullOrEmpty() && juid2.isNotNullOrEmpty()) {
            if (ZsMemeryCache.zsWorkLoginModel?.workModuleUserId == juid2) {
              companyName.value =
              '${value!.data['companyName'] ??
                  ZsMemeryCache.loginDataModel?.userInfo
                      ?.companyName}(综合办公)';
            }
          }
          final ZsWorkLoginModel zsWorkLoginModel = ZsWorkLoginModel(
              ZsMemeryCache.zsWorkLoginModel?.workPath,
              value!.data['sessionId'].toString(),
              value.data['indepOrgId'].toString(),
              userId,
              orgId,
              userName,
              companyName.value);
          ZsMemeryCache.pullToWorkCache(zsWorkLoginModel);
          requestFunction();
          requestNotice();
        }
      }
    }).whenComplete(() {
      onAllData();
      pageStatus.value = PageStatus.normal;
      workStatus.value = PageStatus.normal;
    });
  }

  void requestFunction() {
    get(
        path: zsWorkFunction,
        otherHost: ZsMemeryCache.zsWorkLoginModel!.workPath.toString(),
        queryParams: {
          'userId': ZsMemeryCache.zsWorkLoginModel!.workModuleUserId,
          'fatherId': '',
        }).then((ResultData? value) {
      if (value?.data is List) {
        requestFunctionRedDot();
        webList.value = (value!.data as List)
            .map((e) => ItemModel.fromJson(e, isXB: isXB))
            .toList();
        onAllData();
      }
    }).catchError((e) {
      print(e.toString());
    });
  }

  ///功能红点
  Future<void> requestFunctionRedDot() async {
    try {
      final ResultData? value = await get(
          path: zsWorkFunctionRedDot,
          otherHost: ZsMemeryCache.zsWorkLoginModel!.workPath.toString(),
          queryParams: {
            'userId': ZsMemeryCache.zsWorkLoginModel!.workModuleUserId,
          });
      final List<ZsRedDotModel> dots = ZsRedDotModel.listFormJson(value?.data);

      for (ItemModel item in webList.value) {
        dots.forEach((ZsRedDotModel dot) {
          if (dot.id == item.menuId && dot.count != 0) {
            item.number = dot.count;
          }
          if (dot.id == 'email' && dot.count != 0) {
            emailCount.value = dot.count ?? 0;
          }
        });
      }
    } catch (e) {}
  }

  ///项目详情
  Future<void> requestProjectDetail() async {
    if (ZsMemeryCache.loginDataModel == null) {
      canNew.value = false;
      return;
    }

    ///判断用户有没有公司，没有公司则显示占位页面
    if (ZsMemeryCache.loginDataModel?.userInfo?.companyId == null ||
        ZsMemeryCache.loginDataModel?.userInfo?.companyId == '') {
      canNew.value = false;
      return;
    }

    try {
      final ResultData? value =
      await get(path: '/app/v1.0/cloudLook/getIndex', queryParams: {
        'userId': ZsMemeryCache.loginDataModel!.userInfo!.userId,
        'projectId': projectId,
      });
      if (value!.code == 1) {
        final ZsProjectDetailModel zsProjectDetailModel =
        ZsProjectDetailModel.fromJson(value.data);
        projectDetail.value = zsProjectDetailModel.projectMap!;
        projectId = zsProjectDetailModel.projectMap!.pid!;
        taskNum.value = zsProjectDetailModel.taskNum!;
        canNew.value = true;
        if (callback != null) {
          final Map<String, String> params = {
            'projectId': projectDetail.value.pid ?? '',
            'projectName': projectDetail.value.projectName ?? '',
            'projectStatus': projectDetail.value.status.toString() ?? '',
            'standardProjectType': projectDetail.value.projectTypeId ?? '',
            'projectCode': projectDetail.value.projectCode ?? '',
            'projectTypeName': projectDetail.value.projectType ?? '',
            'industryNatureOne': projectDetail.value.industryNatureOne ?? '',
            'companyId': projectDetail.value.companyId ?? '',
          };
          callback!(params);
        }
        requestAfterGetProject();
      } else {
        canNew.value = false;
      }
    } catch (e) {
      canNew.value = false;
    }

    eventBus.fire(HYEvent(type: HYEventType.appHomeWorkAppNotification));
    pageStatus.value = PageStatus.normal;
  }

  ///公告列表
  void requestNotice() {
    get(
        path: zsWorkNotice,
        otherHost: ZsMemeryCache.zsWorkLoginModel!.workPath.toString(),
        queryParams: {
          'userId': ZsMemeryCache.zsWorkLoginModel!.workModuleUserId,
          'pageNumber': '1',
          'pageSize': '3'
        }).then((ResultData? value) {
      if (value?.data is Map) {
        noticeList.value =
            ZsWorkNoticeListModel.listFormJson(value?.data['notice']);
      }
    }).catchError((e) {
      print(e.toString());
    });
  }

  void intentTaskSchedule() {
    if (Platform.isAndroid) {
      Get.toNamed(ZsRouter.zsWorkProjectTaskScheduleListRouter,
          parameters: {'projectId': projectId, 'id': '', 'title': '任务进度'});
    } else {
      methodChannel.invokeMethod('taskProcessPage', {'projectId': projectId});
    }
  }

  void requestAfterGetProject() {
    requestHasSchedule();
    requestProjectSchedule();
    requestProjectScheduleStatistics();
    requestProjectHistorySchedule();
    if (projectId.isNotEmpty) {
      if (ZsMemeryCache.zsWorkLoginModel?.workPath != WorkPath_YM) {
        onAllData();
      } else {
        routeLogic
            .requestProjectMembersHasProjectMember(projectId)
            .whenComplete(() {
          onAllData();
        });
      }
    }
  }

  ///查询是否有进度
  void requestHasSchedule() {
    get(path: zsProjectSchedulingHas, queryParams: {
      'companyId': ZsMemeryCache.loginDataModel?.userInfo?.companyId,
      'projectId': projectId
    }).then((ResultData? value) {
      if (value!.code == 4001) {
        try {
          hasSchedule = value.data as bool;
        } catch (e) {}
      }
    });
  }

  ///项目总进度
  Future<void> requestProjectSchedule() async {
    post(
        path: zsProjectScheduleProjectAggregate,
        paramType: ParamType.nomarl,
        params: {'projectId': projectId}).then((ResultData? value) {
      if (value!.code == 4001) {
        ZsProjectScheduleBaseData zsProjectScheduleBaseData =
        ZsProjectScheduleBaseData.fromJson(value.data);
        totalSchedule.value =
            double.parse(zsProjectScheduleBaseData.totalSchedule.toString()) /
                100;
        totalScheduler.value =
            zsProjectScheduleBaseData.totalSchedule.toString();
        totalDays.value = zsProjectScheduleBaseData.totalDays.toString();
        finishDays.value = zsProjectScheduleBaseData.finishDays.toString();
        overdue.value = zsProjectScheduleBaseData.overdue!;
      }
    });
  }

  ///进度统计
  Future<void> requestProjectScheduleStatistics() async {
    post(
        path: zsProjectScheduleStatistics,
        paramType: ParamType.nomarl,
        params: {'projectId': projectId}).then((ResultData? value) {
      if (value!.code == 4001) {
        scheduleList.value =
            ZsProjectScheduleStatisticsModel.listFormJson(value.data);
      }
    });
  }

  // todo 项目历史暂无数据，这块目前是写死的
  ///项目历史进度
  Future<void> requestProjectHistorySchedule() async {
    get(path: zsProjectHistorySchedule, queryParams: {
      'companyId': ZsMemeryCache.loginDataModel?.userInfo?.companyId,
      'projectId': projectId
    }).then((ResultData? value) {
      if (value!.code == 4001) {
        ZsProjectHistorySchedule zsProjectHistorySchedule =
        ZsProjectHistorySchedule.fromJson(value.data);
        projectSchedule.value = zsProjectHistorySchedule;
      }
    });
  }

  /// 日志管理
  void logManage() {
    Get.toNamed(ZsRouter.zsWorkLogManage);
  }

  Future<void> routeMethod(String key, url) async {
    final Map<String, dynamic> map = <String, dynamic>{};
    map.put('companyName', ZsMemeryCache.loginDataModel!.userInfo!.companyName);
    map.put('userName', ZsMemeryCache.loginDataModel!.userInfo!.userName);
    map.put('sessionId', ZsMemeryCache.zsWorkLoginModel!.sessionId);
    map.put('orgId', ZsMemeryCache.zsWorkLoginModel!.orgId);
    map.put('indepOrgId', ZsMemeryCache.zsWorkLoginModel!.indepOrgId);
    map.put('host', ZsMemeryCache.zsWorkLoginModel?.workPath);
    map.put('workUserName', ZsMemeryCache.zsWorkLoginModel?.userName);
    map.put('workCompanyName', companyName.value);

    map.put(
        'workModuleUserId', ZsMemeryCache.zsWorkLoginModel!.workModuleUserId);
    map.put('url', url);
    methodChannel.invokeMethod(key, map);
  }
}
